package ks.client.controllers.requests;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ks.client.UserContext;
import ks.client.gui.admin.plugin.listeners.UpdatePluginLists;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.plugin.PluginManager;

/**
 * Controller to process PLUGINS requests from the server that contains the full
 * set of known plugins.
 * <p>
 * 
 * @author Jennifer Hunt
 */
public class PluginsController implements IProcessMessage {

	/** In case we need to process something. */
	Lobby lobby;
	
	/** Construct controller with lobby. */
	public PluginsController(Lobby lobby) {
		this.lobby = lobby;
	}

	/**
	 * Client has received plugins message. Process it.
	 * 
	 * @param m
	 * @return
	 */
	public boolean process(Message m) {
		// Get context
		UserContext context = lobby.getUserContext();
		PluginManager pm = context.getPluginManager();
		
		Node pluginsNode = m.contents();
		
		if (pluginsNode == null || !pluginsNode.getNodeName().equalsIgnoreCase("plugins")) {
			return false;
		}
		
		NodeList pluginInstalledList = pluginsNode.getChildNodes();
		Node pluginInstalledNode;
		NamedNodeMap nnp;
		Node nameNode;
		Node lossesNode;
		Node winsNode;
		Node dateNode;
		Node suspendedNode;
		
		pm.removeAll();
		
		for (int i=0; i<pluginInstalledList.getLength(); i++) {
			pluginInstalledNode = pluginInstalledList.item(i);
			
			if (pluginInstalledNode == null || !pluginInstalledNode.getNodeName().equalsIgnoreCase("plugin-installed")) {
				continue;
			}
			
			nnp = pluginInstalledNode.getAttributes();
			nameNode = nnp.getNamedItem("name");
			lossesNode = nnp.getNamedItem("losses");
			winsNode = nnp.getNamedItem("wins");
			dateNode = nnp.getNamedItem("date");
			suspendedNode = nnp.getNamedItem("suspended");
			
			if (nameNode == null || lossesNode == null || winsNode == null || dateNode == null || suspendedNode == null) {
				continue;
			}
			
			pm.add(nameNode.getNodeValue(), 
					Integer.parseInt(lossesNode.getNodeValue()), 
					Integer.parseInt(winsNode.getNodeValue()), 
					dateNode.getNodeValue(), 
					Boolean.parseBoolean(suspendedNode.getNodeValue()));
			
		}
		
		//updates the list of plugins in the plugin manager gui, and in the admin plugins screen
		new UpdatePluginLists(lobby);
	
		return true;
	}
	
}
